import 'dart:async';

import 'package:flutter/material.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/models/goods/goods_obj.dart';
import 'package:xws/state/app_state.dart';
import 'package:xws/state/user_state.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/utils/data_util.dart';
import 'package:xws/utils/dio_utils/request/goods_req.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/widgets/app_btn.dart';
import 'package:xws/widgets/app_img.dart';
import 'package:xws/widgets/app_list_tile.dart';

import 'send_check.dart';

/// 物品信息块
class GoodsBox extends StatefulWidget {
  const GoodsBox({
    Key? key,
    required this.id,
    this.showGoods,
    required this.toUserId,
    required this.toUserName,
    required this.toUserHeader,
  }) : super(key: key);

  @override
  _GoodsBoxState createState() => _GoodsBoxState();

  final String id;
  final String toUserId;
  final String toUserName;
  final String toUserHeader;

  final Function(bool)? showGoods;
}

class _GoodsBoxState extends State<GoodsBox> with SafeState<GoodsBox> {
  GoodsObj? _goodsObj;

  GoodsObj get _g => _goodsObj!;

  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _initGoods(isInit: true);
  }

  @override
  void dispose() {
    _cancelTimer();
    super.dispose();
  }

  /// 开始计时器
  void _startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 5), (_) {
      _initGoods();
    });
  }

  /// 销毁计时器
  void _cancelTimer() {
    _timer?.cancel();
    _timer = null;
  }

  /// 抓取物品信息
  Future<void> _initGoods({bool isInit = false}) async {
    final List<GoodsObj> gList = await getGoodsList(goodsIdList: <String>[widget.id]);
    if (gList.isNotEmpty) {
      if (_goodsObj?.status != gList.single.status) {
        _goodsObj = gList.single;
        widget.showGoods?.call(true);
        safeSetState(() {});

        if (_goodsObj?.status == GoodsStatus.DELIVERED) {
          if (!isInit) {
            if (_g.toUserId == us.info.id) st('已获赠');
            apps.refreshFriendGoods();
            apps.refreshNearGoods();
          }

          _cancelTimer();
        } else if (isInit) {
          if (us.info.id != _g.user.id) {
            _startTimer();
          }
        }
      }
    } else {
      if (_goodsObj != null) {
        _goodsObj = null;
        widget.showGoods?.call(false);

        safeSetState(() {});
      }
    }
  }

  /// 送出
  Future<void> _give() async {
    final bool? ch = await customDialog<bool>(SendCheck(
      goodsObj: _g,
      user: GoodsUser(name: widget.toUserName, header: widget.toUserHeader),
    ));
    if (ch == null || !ch) return;

    loading(context);
    final bool r = await giveGoods(_g.id, widget.toUserId);
    if (r) await _initGoods();
    close(context);
  }

  @override
  Widget build(BuildContext context) {
    return _goodsObj == null
        ? const SizedBox.shrink()
        : Stack(
            children: <Widget>[
              Container(
                width: sw,
                height: 100,
                color: white(context),
                padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                child: AppListTile(
                  leading: Padding(
                    padding: const EdgeInsets.only(right: 14),
                    child: AppImg.fitCover(
                      url: _g.photoUrlList.first,
                      width: 70,
                      height: 70,
                      radius: 10,
                    ),
                  ),
                  title: Text(
                    _g.description,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                      color: black(context).withOpacity(0.8),
                    ),
                  ),
                  subtitle: Row(
                    children: <Widget>[
                      _buildLable(_g.city, theme(context)),
                      const SizedBox(width: 8),
                      _buildLable(getQualityValue(_g.age), theme2(context)),
                      const Spacer(),
                      if (_g.userId == us.info.id && _g.status == GoodsStatus.SHOWING)
                        AppBtn(
                          onTap: _give,
                          text: '赠予',
                          height: 30,
                          alignment: Alignment.center,
                          padding: const EdgeInsets.symmetric(horizontal: 14),
                        ),
                    ],
                  ),
                ),
              ),
              _buildStatus,
            ],
          );
  }

  Widget _buildLable(String content, Color color) {
    return Container(
      height: 24,
      child: Text(
        content,
        style: TextStyle(
          color: color.withOpacity(0.8),
          fontSize: 11,
          fontWeight: FontWeight.bold,
          height: 1.2,
        ),
      ),
      alignment: Alignment.center,
      padding: const EdgeInsets.symmetric(horizontal: 5),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(4),
      ),
    );
  }

  /// 构建物品状态
  Widget get _buildStatus {
    if (_g.status == GoodsStatus.SHOWING) return const SizedBox.shrink();

    if (_g.toUserId == us.info.id) return _buildStatusCircle('已获得', theme(context).withOpacity(0.2));

    return _buildStatusCircle('已送出', black(context).withOpacity(0.1));
  }

  Widget _buildStatusCircle(String text, Color color) {
    return Positioned(
      top: 0,
      bottom: 0,
      right: 20,
      child: Transform.rotate(
        angle: 0.5,
        child: Container(
          width: 90,
          height: 90,
          alignment: Alignment.center,
          child: Text(
            text,
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.w900,
              color: color,
            ),
          ),
          decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(
                color: color,
                width: 6,
              )),
        ),
      ),
    );
  }
}
